﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Ports;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HandyControl.Controls;
using MyHelper;
using ScaleDataInterpreter;

namespace weighing
{
    /// <summary>
    /// ScaleContent.xamlv 磅称数据显示模块 的交互逻辑
    /// </summary>
    public partial class ScaleContent : System.Windows.Controls.UserControl
    {
        #region   
        private bool isRefreshing = false;
        protected List<SerialPort>? mSerialPortList;
        public List<ScaleVo>? mScaleVoList = new List<ScaleVo>();
        #endregion

        public ScaleContent()
        {
            InitializeComponent();
            if (DesignerProperties.GetIsInDesignMode(this)) return;

            this.Loaded += ScaleContent_Loaded;
            this.Unloaded += ScaleContent_Unloaded;
        }

        private void ScaleContent_Unloaded(object sender, RoutedEventArgs e)
        {
            if (mScaleVoList != null)
            {
                foreach (var item in mScaleVoList)
                {
                    item.DisposeTimer();
                    item.DisposeSerialPort();
                    item.SerialPort = null;
                }
            }

        }

        private void ScaleContent_Loaded(object sender, RoutedEventArgs e)
        {
            GetScales();
            ShowScale();
        }

        /// <summary>
        /// 显示
        /// </summary>
        private void ShowScale()
        {
            if (mScaleVoList?.Count <= 0)
            {
                var msg = "系统 没有添加磅称 ，数量为1到2 台。";
                Growl.InfoGlobal(msg);
                return;
            }
            if (mScaleVoList?.Count > 0 || isRefreshing)
            {
                this.mainPanel.Children.Clear();
            }
            mSerialPortList = new List<SerialPort>();
            for (int i = 0; i < mScaleVoList?.Count; i++)
            {
                ScaleVo vo = mScaleVoList[i];
                if (vo.IsVirtual == false)
                {
                    SerialPort port = new()
                    {
                        BaudRate = vo.BaudRate ?? 9600,
                        PortName = vo.Com,
                        DataBits = 8,
                        StopBits = StopBits.One,
                        Parity = Parity.None,
                    };
                    vo.SerialPort = port;
                    //没有品牌就以耀华的来解释
                    vo.Interpreter = DataInterpreter.GetDataInterpreter((int)vo.BrandType, port);
                }
            }
            App.scaleItems = new List<ScaleItem>();
            for (int i = 0; i < mScaleVoList?.Count; i++)
            {
                ScaleItem scaleItem = new ScaleItem()
                {
                    Name = "scale" + i,
                    DataContext = null,
                    Margin = new Thickness(5),
                    Width = 300
                };
                scaleItem.DataContext = mScaleVoList[i];
                this.mainPanel.Children.Add(scaleItem);
                App.scaleItems.Add(scaleItem);//保存到APP 内其它地方用
            }

        }
        /// <summary>
        /// 获取当前磅称 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public ScaleVo? GetCurrentScale(WeightingBillType type)
        {
            ScaleVo? vo = null;
            if (App.scaleItems == null || App.scaleItems.Count <= 0) return null;
            if (App.scaleItems.Count == 1)
            {
                App.scaleItems[0].IsSelected = true;
                vo = App.scaleItems[0].DataContext as ScaleVo;
                return vo;
            }

            //基础版本 ，如果有选中，优先

            for (int i = 0; i < App.scaleItems.Count; i++)
            {
                if (App.scaleItems[i].IsSelected == true)
                {
                    return App.scaleItems[i].DataContext as ScaleVo;
                }
            }

            //取消所有的选中   
            ScaleItem scale;
            for (int i = 0; i < App.scaleItems.Count; i++)
            {
                scale = App.scaleItems[i];
                scale.IsSelected = false;
            }

            //优先默认
            for (int i = 0; i < App.scaleItems.Count; i++)
            {
                var temp = App.scaleItems[i].DataContext as ScaleVo;
                if (temp != null && temp.DefaultType == (int)type)
                {
                    App.scaleItems[i].IsSelected = true;
                    vo = temp;
                }
                else
                {
                    App.scaleItems[i].IsSelected = false;
                }
            }
            return vo;
        }

        private void StartReadData()
        {

            if (mScaleVoList?.Count <= 0)
            {
                var msg = "系统 没有添加磅称 ，数量为1到2 台。";
                Growl.InfoGlobal(msg);
                return;
            }
            if (mScaleVoList?.Count > 0)
            {
                this.mainPanel.Children.Clear();
            }
            if (isRefreshing)
            {
                this.mainPanel.Children.Clear();
            }
            mSerialPortList = new List<SerialPort>();
            for (int i = 0; i < mScaleVoList?.Count; i++)
            {
                ScaleVo vo = mScaleVoList[i];
                SerialPort port = new SerialPort()
                {
                    BaudRate = vo.BaudRate ?? 9600,
                    PortName = vo.Com,
                    DataBits = 8,
                    StopBits = StopBits.One,
                    Parity = Parity.None,
                };
                vo.SerialPort = port;
                //没有品牌就以耀华的来解释
                vo.Interpreter = DataInterpreter.GetDataInterpreter((int)vo.BrandType, port);
            }
            App.scaleItems = new List<ScaleItem>();
            for (int i = 0; i < mScaleVoList?.Count; i++)
            {
                ScaleItem scaleItem = new ScaleItem()
                {
                    Name = "scale" + i,
                    DataContext = null,
                    Margin = new Thickness(5),
                    Width = 300
                };
                scaleItem.DataContext = mScaleVoList[i];
                this.mainPanel.Children.Add(scaleItem);
                App.scaleItems.Add(scaleItem);//保存到APP 内其它地方用

            }
        }
        private void GetScales()
        {
            var list = ScaleDao.Instance.GetList();
            mScaleVoList?.Clear();
            mScaleVoList = list?.Select((i) => { return new ScaleVo(i); }).ToList();
        }

        public void ChangeDataContent(Int32 index, String property, object value)
        {
            if (index < 0 || index >= mScaleVoList?.Count)
            {
                return;
            }
            PropertyInfo? propertyInfo = typeof(ScaleVo).GetProperty(property);
            propertyInfo?.SetValue(this.mScaleVoList?[index], value);
        }
        public void ChangeActiveScaleDataContent(String property, object value)
        {
            if (mScaleVoList == null || mScaleVoList.Count == 0) return;
            PropertyInfo? propertyInfo = typeof(ScaleVo).GetProperty(property);

            if (mScaleVoList.Count == 1)
            {
                propertyInfo?.SetValue(this.mScaleVoList[0], value);
                return;
            }
            for (int i = 0; i < App.scaleItems.Count; i++)
            {
                ScaleItem item = App.scaleItems[i];
                ScaleVo? vo = item.DataContext as ScaleVo;
                if (item.IsSelected == true)
                {
                    Console.WriteLine(vo?.Name + ": " + propertyInfo?.Name + " set value:" + value);
                    propertyInfo.SetValue(vo, value);
                }
            }

        }
        public void ChangeScaleDataContent(string scaleName, String property, object value)
        {
            if (mScaleVoList == null || mScaleVoList.Count == 0) return;
            ScaleVo? vo;
            if (mScaleVoList.Count == 1)
            {
                vo = mScaleVoList[0];
            }
            else
            {
                vo = this.mScaleVoList.Find((i) => i.Name == scaleName);
            }
            if (vo != null && vo.IsVirtual)
            {
                PropertyInfo? propertyInfo = typeof(ScaleVo).GetProperty(property);
                propertyInfo?.SetValue(vo, value);
            }

        }

        public void RefreshMi_Click(object sender, RoutedEventArgs e)
        {
            isRefreshing = true;
            if (this.mScaleVoList?.Count > 0)
            {
                this.mainPanel.Children.Clear();
                for (int i = 0; i < mScaleVoList.Count; i++)
                {
                    ScaleVo item = mScaleVoList[i];
                    item.DisposeTimer();
                    item.DisposeSerialPort();
                    item.SerialPort = null;
                }
            }
            mScaleVoList?.Clear();
            ScaleContent_Loaded(sender, e);
        }

        private void AddHl_Click(object sender, RoutedEventArgs e)
        {
            new ScaleWindow() { Owner = App.Current.MainWindow }.Show();
        }

        public void RefreshHi_Click(object sender, RoutedEventArgs e)
        {
            RefreshMi_Click(sender, e);
        }
    }
}
